<!-- 选择学生组件 -->
<template>
  <div class="type-class-box" ref="studentRef">
    <el-tabs v-model="activeTab" @tab-change="onChangTab">
      <el-tab-pane
        label="选择班级"
        name="1"
        :disabled="getCheckedStudentList().length > 0"
      ></el-tab-pane>
      <el-tab-pane
        label="选择学生"
        name="2"
        :disabled="activeClassList.length > 0"
      ></el-tab-pane>
    </el-tabs>

    <template v-if="activeTab === '1'">
      <div
        class="class-box"
        v-for="(classType, index) in classTypeList"
        :key="index"
      >
        <template
          v-if="
            (nowGlobalRole.role_code === ROLE_ENUM.Planner ||
              nowGlobalRole.role_code === ROLE_ENUM.StoreManager) &&
            index <= 1
          "
        ></template>
        <template v-else>
          <div class="tool-box flex-between">
            <el-checkbox
              v-model="classType.checkAll"
              @change="param => onCheckAllClass(param, index)"
              :disabled="!classType.classList.length"
            >
              {{ classType.text }}
            </el-checkbox>
          </div>
          <div class="class-list flex">
            <div
              v-for="(classItem, classIndex) in classType.classList"
              class="class-select hover"
              :class="[
                activeClassList.indexOf(classItem.value) !== -1 &&
                  'class-select-active'
              ]"
              @click="onSelectClassTab1(classItem, index)"
              :key="classIndex"
            >
              {{ classItem.label }}
            </div>
            <div v-if="!classType.classList.length" class="text">
              暂无{{ classType.text }}
            </div>
          </div>
        </template>
      </div>
    </template>
    <template v-else-if="activeTab === '2'">
      <div class="list-box flex">
        <div class="box-left flex-column">
          <div
            class="list-item text-ellipsis hover"
            :class="[
              activeClass?.value === classItem.value && 'list-item-active'
            ]"
            :title="classItem.label"
            v-for="(classItem, index) in showClassList"
            :key="index"
            @click="onSelectClassTab2(classItem)"
          >
            {{ classItem.label }}
            <div class="dot" v-if="getCheckedNum(classItem).length">
              {{ getCheckedNum(classItem).length }}
            </div>
          </div>
        </div>
        <div class="box-right">
          <div class="flex-between tool-box">
            <el-checkbox
              class="select-layer"
              @change="onChangeCheckAll"
              v-model="checkAllStudent"
            >
              全部
            </el-checkbox>
            <el-checkbox class="select-layer" v-model="checkLayer">
              启动分层
            </el-checkbox>
          </div>
          <div class="class-box flex" v-if="!checkLayer">
            <div class="class-list flex">
              <div
                v-for="(student, index) in showAllStudentList"
                class="class-select hover"
                :class="[student.checked && 'class-select-active']"
                @click="onCheckStudent(student)"
                :key="index"
              >
                {{ student.student_name }}
              </div>
            </div>
          </div>
          <template v-else>
            <div
              class="class-box"
              v-for="(checkedItem, index) in activeClass.checkedList"
              :key="index"
            >
              <el-checkbox
                class="select-layer"
                @change="param => onChangeCheckLayerAll(param, index)"
                v-model="activeClass.checkedList[index]"
                :disabled="!activeClass.layerList[index]?.length"
              >
                {{
                  index === 0
                    ? '待分层学生'
                    : String.fromCharCode(index + 64) + '层学生'
                }}
              </el-checkbox>
              <div class="class-list flex">
                <div
                  v-for="(student, studentIndex) in activeClass.layerList[
                    index
                  ]"
                  class="class-select hover"
                  :class="[student.checked && 'class-select-active']"
                  @click="onCheckStudent(student)"
                  :key="studentIndex"
                >
                  {{ student.student_name }}
                </div>
                <span v-if="!activeClass.layerList[index]?.length"
                  >此层无学生</span
                >
              </div>
            </div>
          </template>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, defineExpose, watch, computed, nextTick, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth-store'
import { getLayeredStudentList } from '@/apis/assignment/index'
import { CLASS_TYPE } from '@/views/assignment/util'
import { ROLE_ENUM } from '@/stores/auth-store'
import dayjs from 'dayjs'

const classTypeList = defineModel('classTypeList')
const activeTab = defineModel('activeTab')
const activeClassList = defineModel('activeClassList')

const props = defineProps({
  selectClassInfo: {
    default: []
  }
})

const studentRef = ref()
const {
  nowGlobalSubjectId,
  getClassListOfSubject,
  nowGlobalRole,
  userInfo,
  getTeachingInfo
} = useAuthStore()

const activeClass = ref() // tab2 当前班级

const checkLayer = ref(false) // 启动分层
const checkAllStudent = ref(false) // 全选学生

/**
 * tab1展示班级列表
 */
classTypeList.value = [
  {
    text: '行政班',
    checkAll: false,
    classList: []
  },
  {
    text: '教学班',
    checkAll: false,
    classList: []
  },
  {
    text: '靶向班',
    checkAll: false,
    classList: []
  },
  {
    text: '爱学班',
    checkAll: false,
    classList: []
  }
]

/**
 * tab2展示左侧班级列表
 */
const showClassList = computed(() => {
  return [
    ...classTypeList.value[0].classList,
    ...classTypeList.value[1].classList,
    ...classTypeList.value[2].classList,
    ...classTypeList.value[3].classList
  ]
})

const onChangTab = () => {
  activeClass.value = showClassList.value[0]
  if (!activeClass.value.layerList.length) {
    getLayeredStudentListInfo()
  }
}

/**
 *  tab1 选中/取消选中班级
 * @param {*} classItem
 */
const onSelectClassTab1 = (classItem, typeIndex) => {
  if (classItem) {
    let index = activeClassList.value.indexOf(classItem.value)
    if (index === -1) {
      activeClassList.value.push(classItem.value)
    } else {
      activeClassList.value.splice(index, 1)
    }
  }

  let res = classTypeList.value[typeIndex].classList.find(
    item => activeClassList.value.indexOf(item.value) === -1
  )
  classTypeList.value[typeIndex].checkAll = res ? false : true
}

// tab2 -----------------------
/**
 * tab2 获取分层数据
 */
const getLayeredStudentListInfo = async (typeClass, studentIds) => {
  const paramClass = typeClass || activeClass.value
  const res = await getLayeredStudentList({
    class_id: String(paramClass.value),
    subject_id: nowGlobalSubjectId || 'all',
    task_from: 1,
    layer_type: 3,
    start_time: dayjs().subtract(6, 'month').startOf('date').unix(),
    end_time: dayjs().unix(),
    teacher_id: userInfo.userId,
    school_id: userInfo.school_id
  })
  const { students, a_students, b_students, c_students } = res.data
  paramClass.layerList = [
    (students || []).map(student => ({
      ...student,
      checked: studentIds
        ? studentIds.indexOf(student.student_id) !== -1
        : false
    })),
    (a_students || []).map(student => ({
      ...student,
      checked: studentIds
        ? studentIds.indexOf(student.student_id) !== -1
        : false
    })),
    (b_students || []).map(student => ({
      ...student,
      checked: studentIds
        ? studentIds.indexOf(student.student_id) !== -1
        : false
    })),
    (c_students || []).map(student => ({
      ...student,
      checked: studentIds
        ? studentIds.indexOf(student.student_id) !== -1
        : false
    }))
  ]
}

/**
 * tab2 选中班级
 */
const onSelectClassTab2 = async classItem => {
  activeClass.value = classItem
  !activeClass.value.layerList.length && (await getLayeredStudentListInfo())
}

const getCheckedNum = classItem => {
  let list = []
  if (classItem.layerList.length) {
    classItem.layerList.forEach(layer => {
      list.push(...layer.filter(student => student.checked))
    })
  }
  return list
}

const getCheckedStudentList = () => {
  let list = []
  classTypeList.value.forEach(classType => {
    classType.classList.forEach(classItem => {
      list.push(...getCheckedNum(classItem))
    })
  })
  return list
}

// 全部全选
const onChangeCheckAll = param => {
  if (!activeClass.value.layerList.length) return
  activeClass.value.layerList.forEach(layer => {
    layer.forEach(student => (student.checked = param))
  })
}

// tab1 全选班级类型
const onCheckAllClass = (param, index) => {
  classTypeList.value[index].classList.forEach(classItem => {
    let classIndex = activeClassList.value.indexOf(classItem.value)
    if (param && classIndex === -1) {
      activeClassList.value.push(classItem.value)
    } else if (!param && classIndex !== -1) {
      activeClassList.value.splice(classIndex, 1)
    }
  })
}

// 分层全选
const onChangeCheckLayerAll = (param, index) => {
  activeClass.value.checkedList[index] = param
  activeClass.value.layerList[index].forEach(
    student => (student.checked = param)
  )
}

const onCheckStudent = student => {
  student.checked = !student.checked
}

const showAllStudentList = computed(() => {
  if (activeClass.value) {
    let list = []
    activeClass.value.layerList.forEach(layer => list.push(...layer))
    return list
  }
  return []
})

watch(
  () => activeClass.value?.layerList,
  () => {
    activeClass.value.layerList.forEach((layer, index) => {
      if (layer.length && !layer.filter(student => !student.checked).length) {
        activeClass.value.checkedList[index] = true
      } else {
        activeClass.value.checkedList[index] = false
      }
    })
  },
  {
    deep: true
  }
)
watch(
  () => showAllStudentList.value,
  () => {
    if (!showAllStudentList.value.length) return
    if (showAllStudentList.value.find(student => !student.checked)) {
      checkAllStudent.value = false
    } else {
      checkAllStudent.value = true
    }
  },
  {
    deep: true
  }
)

// 初始化班级数据
const initData = async () => {
  await getTeachingInfo(nowGlobalRole.role_code)
  const data = await getClassListOfSubject(nowGlobalSubjectId)
  let adminTeachClass = data.filter(item => item.value > 0)
  let targetClass = data.filter(item => item.value == 0)
  let smartClass = data.filter(item => item.value == '-1')

  let classlist = []
  adminTeachClass.forEach(item => {
    item.children.forEach(child => {
      classlist.push({
        ...child,
        label: item.label + child.label,
        class_type: child.class_type
      })
    })
  })
  targetClass.forEach(item => {
    item.children.forEach(child => {
      classlist.push({
        ...child,
        class_type: CLASS_TYPE.TargetClass
      })
    })
  })
  smartClass.forEach(item => {
    item.children.forEach(child => {
      classlist.push({
        ...child,
        class_type: CLASS_TYPE.SmartClass
      })
    })
  })

  classlist.forEach(item => {
    switch (item.class_type) {
      case CLASS_TYPE.AdminClass:
        classTypeList.value[0].classList.push({
          ...item,
          checkedList: [false, false, false, false],
          layerList: []
        })
        break
      case CLASS_TYPE.TeachClass:
        classTypeList.value[1].classList.push({
          ...item,
          checkedList: [false, false, false, false],
          layerList: []
        })
        break
      case CLASS_TYPE.TargetClass:
        classTypeList.value[2].classList.push({
          ...item,
          checkedList: [false, false, false, false],
          layerList: []
        })
        break
      case CLASS_TYPE.SmartClass:
        classTypeList.value[3].classList.push({
          ...item,
          checkedList: [false, false, false, false],
          layerList: []
        })
        break
    }
  })

  // 有初始值的情况下
  // 选择的是全班
  if (
    props.selectClassInfo.length &&
    !props.selectClassInfo[0].student_ids.length
  ) {
    activeClassList.value = props.selectClassInfo.map(classItem =>
      String(classItem.class_id)
    )
    nextTick(() => {
      classTypeList.value.forEach((_, index) => {
        onSelectClassTab1(null, index)
      })
    })
    activeTab.value = '1'
  }
  // 选择的是学生
  else if (props.selectClassInfo.length) {
    for (let i = 0; i < props.selectClassInfo.length; i++) {
      const classItem = props.selectClassInfo[i]
      let item = null
      classTypeList.value.find(typeList => {
        const res = typeList.classList.find(
          list => list.value == classItem.class_id
        )
        item = res || null
        return item
      })
      if (item) {
        await getLayeredStudentListInfo(item, classItem.student_ids)
      }
    }

    onChangTab()
    activeTab.value = '2'
  }
}

onMounted(() => {
  initData()
})

defineExpose({ getCheckedStudentList })
</script>

<!-- eslint-disable -->
<style lang="less" scoped>
.type-class-box {
  height: 100%;
  :deep(.el-tabs__nav-wrap::after) {
    height: 0;
  }
  .class-box {
    .class-list {
      flex-wrap: wrap;
      margin-top: 10px;
      margin-bottom: 20px;
      gap: 14px 16px;
      .text {
        color: #a8abb2;
      }
      .class-select {
        background-color: #f2f4f9;
        border-radius: 4px;
        line-height: 1.8;
        padding: 0 16px;
      }
      .class-select-active {
        background-color: #5466e7;
        color: #fff;
      }
    }
  }
  .list-box {
    height: calc(100% - 60px);
    // background-color: #5466e7;
    align-items: self-start;
    .box-left {
      background-color: #fbfbfb;
      border-radius: 12px;
      height: 100%;
      width: 140px;
      overflow-y: auto;
      .list-item {
        line-height: 3;
        width: 100%;
        text-align: center;
        position: relative;
        overflow: unset;
        overflow-x: clip;
        .dot {
          position: absolute;
          width: 18px;
          height: 18px;
          border-radius: 100%;
          background-color: #da2727;
          color: #fff;
          top: 4px;
          right: 10px;
          z-index: 1;
          font-size: 10px;
          line-height: 18px;
        }
      }
      .list-item-active {
        color: #5466e7;
        &::after {
          content: '';
          display: block;
          width: 2px;
          height: 16px;
          background-color: #5466e7;
          position: absolute;
          top: 50%;
          right: 0;
          transform: translateY(-40%);
        }
      }
    }
    .box-right {
      flex: 1;
      box-sizing: border-box;
      padding: 10px 16px;
      height: 100%;
      overflow-y: auto;
    }
  }
}
</style>
